package com.tdx.blog_nowcoder.controller;

import com.alibaba.fastjson.JSONObject;
import com.tdx.blog_nowcoder.constant.KafkaTopicConstant;
import com.tdx.blog_nowcoder.dao.MessageMapper;
import com.tdx.blog_nowcoder.entity.Message;
import com.tdx.blog_nowcoder.entity.User;
import com.tdx.blog_nowcoder.service.MessageService;
import com.tdx.blog_nowcoder.service.UserService;
import com.tdx.blog_nowcoder.utils.DumpJSONToString;
import com.tdx.blog_nowcoder.utils.Page;
import com.tdx.blog_nowcoder.utils.ThreadHostHolder;
import org.apache.ibatis.annotations.Mapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.HtmlUtils;

import java.util.*;

import static com.tdx.blog_nowcoder.constant.KafkaTopicConstant.*;

@Controller
@RequestMapping("/message")
public class MessageController {
    private static final Logger logger  = LoggerFactory.getLogger(MessageController.class);
    @Autowired
    private ThreadHostHolder hostHolder;

    @Autowired
    private UserService userService;

    @Autowired
    private MessageService messageService;

    @RequestMapping(path = "/list",method = RequestMethod.GET)
    public String getMessagepage(Model model, Page page){
        User user = hostHolder.getUser();
        if(user==null){
            throw new IllegalArgumentException("用户信息异常！");
        }
        page.setPath("/message/list");
        page.setPerPageSize(5);
        page.setTotalPageNums(messageService.selectConversationCount(user.getId()));
        //回话列表
        List<Message> msg_list = messageService.selectConversationsByUserId(user.getId(),
                page.getOffset(),page.getPerPageSize());
        List<Map<String,Object>> conversationList = new ArrayList<>();
        if(msg_list!=null){
            for(Message message:msg_list){
                Map<String,Object> map = new HashMap<>();
                map.put("message",message);
                map.put("letterCount",messageService.findMessageCount(message.getConversationId()));
                map.put("unreadCount",messageService.findMessageUnReadCount(user.getId(),message.getConversationId()));
                //获取回话的另一方用户
                int targetId = user.getId() == message.getFromId() ? message.getToId() : message.getFromId();
                map.put("target", userService.selectUserById(targetId));
                conversationList.add(map);
            }
        }
        model.addAttribute("conversations", conversationList);
        // 查询未读消息数量
        int letterUnreadCount = messageService.findMessageUnReadCount(user.getId(), null);
        model.addAttribute("letterUnreadCount", letterUnreadCount);

        // 未读通知数量
        //通知
        int noticeUnreadCount = messageService.findNoticesUnreadCount(user.getId(), null);
        model.addAttribute("noticeUnreadCount", noticeUnreadCount);

        return "/site/letter";
    }

    // /detail/111_116
    @RequestMapping(path = "/detail/{conversationId}",method = RequestMethod.GET)
    public String getMessageDetail(@PathVariable("conversationId") String conversationId,
                                   Model model,Page page){
        System.out.println(conversationId);
        // 分页信息
        page.setPerPageSize(5);
        page.setPath("/message/detail/" + conversationId);
        page.setTotalPageNums(messageService.findMessageCount(conversationId));

        List<Message> letterList = messageService.findLettersByConversation(conversationId,
                page.getOffset(),page.getPerPageSize());
        List<Map<String,Object>> letters = new ArrayList<>();
        
        if(letterList!=null){
            for (Message message : letterList) {
                Map<String,Object> lettermap = new HashMap<>();
                lettermap.put("message",message);
                lettermap.put("fromUser", userService.selectUserById(message.getFromId()));
                letters.add(lettermap);
            }
        }
        model.addAttribute("letters", letters);

        // 私信目标
        model.addAttribute("target", getLetterTarget(conversationId));


        // 设置已读 查询当前登入用户是接收方
        List<Integer> ids = getLetterIds(letterList);
        if (!ids.isEmpty()) {
            messageService.readMessage(ids); // 更改消息的status为1
        }

        return "/site/letter-detail";
    }

    private List<Integer> getLetterIds(List<Message> letterList) {
        List<Integer> ids = new ArrayList<>();

        if (letterList != null) {
            for (Message message : letterList) {
                // 消息的状态是未读状态 0
                if (hostHolder.getUser().getId() == message.getToId() && message.getStatus() == 0) {
                    ids.add(message.getId());
                }
            }
        }

        return ids;
    }

    private User getLetterTarget(String conversationId) {
        String[] ids = conversationId.split("_");
        int id0 = Integer.parseInt(ids[0]); // from_id
        int id1 = Integer.parseInt(ids[1]); // To_id

        if (hostHolder.getUser().getId() == id0) {
            return userService.selectUserById(id1);  // 查询接收人
        } else {
            return userService.selectUserById(id0);  //查询发起人
        }
    }


    @RequestMapping(path = "/send",method = RequestMethod.POST)
    @ResponseBody
    public String sendMessage(String targetName,String content){

        User target = userService.findUserByName(targetName);
        if (target == null) {
            return DumpJSONToString.getJsonString(404, "目标用户不存在!");
        }

        Message message = new Message();
        message.setFromId(hostHolder.getUser().getId());
        message.setToId(target.getId());
        if (message.getFromId() < message.getToId()) {
            message.setConversationId(message.getFromId() + "_" + message.getToId());
        } else {
            message.setConversationId(message.getToId() + "_" + message.getFromId());
        }
        message.setContent(content);
        message.setCreateTime(new Date());
        messageService.addMessage(message);
        return DumpJSONToString.getJsonString(200,"发送成功！");
    }


    // 系统通知类的页面

    @RequestMapping(path = "/notices/list",method = RequestMethod.GET)
    public String getNoticePage(Model model){
        User user = hostHolder.getUser();
        //评论类的通知
        Message comment_notice = messageService.findLatestNotice(user.getId(), KafkaTopicConstant.TOPIC_COMMENT);
        // Message{id=275, fromId=1, toId=146, conversationId='comment',
        // content='{"entityType":1,"entityId":274,"postId":274,"userId":111}', status=0,
        // createTime=Thu May 16 02:26:59 CST 2019}


        if(comment_notice!=null){
            Map<String,Object> CommentNoticeVo = new HashMap<>();
            CommentNoticeVo.put("comment_notice",comment_notice);
            String content = HtmlUtils.htmlUnescape(comment_notice.getContent());
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);
            //评论用户
            CommentNoticeVo.put("user",userService.selectUserById((Integer) data.get("userId")));
            CommentNoticeVo.put("entityType", data.get("entityType"));

            //消息数量
            int count = messageService.findNoticesCount(user.getId(), TOPIC_COMMENT);
            CommentNoticeVo.put("count", count);

            //未读数量
            int unread = messageService.findNoticesUnreadCount(user.getId(), TOPIC_COMMENT);
            CommentNoticeVo.put("unread", unread);

            CommentNoticeVo.put("com_topic",TOPIC_COMMENT);
            model.addAttribute("CommentNoticeVo",CommentNoticeVo);
        }else if(comment_notice==null) {
            model.addAttribute("CommentNoticeVo",null);
        }


        //
        // 查询点赞类通知
        Message like_notice = messageService.findLatestNotice(user.getId(), TOPIC_LIKE);
        if(like_notice!=null){
            Map<String,Object> LikleNoticeVo = new HashMap<>();
            LikleNoticeVo.put("like_notice",like_notice);
            String content = HtmlUtils.htmlUnescape(like_notice.getContent());
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);
            //评论用户
            LikleNoticeVo.put("user",userService.selectUserById((Integer) data.get("userId")));
            LikleNoticeVo.put("entityType", data.get("entityType"));

            //消息数量
            int count = messageService.findNoticesCount(user.getId(), TOPIC_LIKE);
            LikleNoticeVo.put("count", count);

            //未读数量
            int unread = messageService.findNoticesUnreadCount(user.getId(), TOPIC_LIKE);
            LikleNoticeVo.put("unread", unread);

            LikleNoticeVo.put("like_topic",TOPIC_LIKE);
            model.addAttribute("LikleNoticeVo",LikleNoticeVo);
        }else if(like_notice==null) {
            model.addAttribute("LikleNoticeVo",null);
        }



        // 查询关注类通知
        Message follow_notice = messageService.findLatestNotice(user.getId(), TOPIC_FOLLOW);

        if(follow_notice!=null){
            Map<String,Object> FollowNoticeVo = new HashMap<>();
            FollowNoticeVo.put("follow_notice",follow_notice);
            String content = HtmlUtils.htmlUnescape(follow_notice.getContent());
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);
            //评论用户
            FollowNoticeVo.put("user",userService.selectUserById((Integer) data.get("userId")));
            FollowNoticeVo.put("entityType", data.get("entityType"));

            //消息数量
            int count = messageService.findNoticesCount(user.getId(), TOPIC_FOLLOW);
            FollowNoticeVo.put("count", count);

            //未读数量
            int unread = messageService.findNoticesUnreadCount(user.getId(), TOPIC_FOLLOW);
            FollowNoticeVo.put("unread", unread);

            FollowNoticeVo.put("follow_topic",TOPIC_FOLLOW);
            model.addAttribute("FollowNoticeVo",FollowNoticeVo);
        } else if (follow_notice==null) {
            model.addAttribute("FollowNoticeVo",null);
        }


        // 查询未读消息数量
        //私信
        int letterUnreadCount = messageService.findMessageUnReadCount(user.getId(), null);
        model.addAttribute("letterUnreadCount", letterUnreadCount);
        //通知
        int noticeUnreadCount = messageService.findNoticesUnreadCount(user.getId(), null);
        model.addAttribute("noticeUnreadCount", noticeUnreadCount);

        return "/site/notice";
    }


    @RequestMapping(path = "/topic-detail/{topic}",method = RequestMethod.GET)
    public String topicDetaiPage(@PathVariable("topic") String topic,Page page,Model model){
        if(!(topic.equals(TOPIC_COMMENT)||topic.equals(TOPIC_FOLLOW)||topic.equals(TOPIC_LIKE))){
            logger.error("触发主题事件有误！"+topic);
            System.out.println("----------------------");
            throw  new IllegalArgumentException("topic 信息异常");
        }
        User user = hostHolder.getUser();
        //设置分页的信息
        page.setPerPageSize(5);
        page.setPath("/message/topic-detail/"+topic);
        page.setTotalPageNums(messageService.findNoticesCount(user.getId(),topic));

        // 查询所有的消息

        List<Message> noticeList = messageService.findNoticesList(user.getId(), topic, page.getOffset(), page.getPerPageSize());
        if (noticeList != null) {
            List<Map<String, Object>> noticeVoList = new ArrayList<>();
            for (Message notice : noticeList) {
                Map<String, Object> map = new HashMap<>();
                // 通知
                map.put("notice", notice);
                // 内容
                String content = HtmlUtils.htmlUnescape(notice.getContent());
                Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);

                map.put("user", userService.selectUserById((Integer) data.get("userId")));

                map.put("entityType", data.get("entityType"));
                map.put("entityId", data.get("entityId"));
                map.put("postId", data.get("postId"));
                // 通知来源作者(系统用户)
                map.put("fromUser", userService.selectUserById(notice.getFromId()));
                map.put("notice_time",notice.getCreateTime());

                noticeVoList.add(map);
            }
            model.addAttribute("notices", noticeVoList);
        } else if (noticeList==null) {
            model.addAttribute("notices", null);
        }

        // 设置已读
        List<Integer> ids = getLetterIds(noticeList);
        if (!ids.isEmpty()) {
            messageService.readMessage(ids);
        }

        return "/site/notice-detail";
    }

}
